<template>
	<view class="code-input-container flex-row">
		<input placeholder="请输入验证码" @input="inputCode" v-model="code" :maxlength="6" type="text">
		<text class="send-verification-code" @click="sendCode">{{codeTips}}</text>
	</view>
</template>

<script>
	import {
		validatePhoneNumber
	} from '@/utils/validate.js';
	import {
		getCode,
	} from '@/api/login';
	export default {
		props: {
			type: {
				type: String,
				default: '1',
			},
			phoneNumber: {
				type: String,
				default: '',
			},
			value: {
				type: String,
				default: '',
			}
		},
		data() {
			return {
				code: '',
				isSend: false,
				secondNumber: 60,
			}
		},
		computed: {
			codeTips() {
				if (this.secondNumber === 60) {
					return '发送验证码';
				} else {
					return `${this.secondNumber}秒后重新发送`
				}
			}
		},
		methods: {
			inputCode(data) {
				this.$emit('input', data.detail.value)
			},
			handleCode(code) {
				if (!code) {
					uni.showToast({
						title: '验证码发送失败',
						icon: 'none',
					})
					return;
				} else {
					// 临时将验证码显示出来
					uni.showToast({
						title: `验证码已发送：${code}`,
						icon: 'none',
					})
					this.codeTimer = setInterval(() => {
						this.secondNumber--;
						if (this.secondNumber < 0) {
							this.secondNumber = 60;
							this.isSend = false;
							clearInterval(this.codeTimer)
						}
					}, 1000)
				}
			},
			async sendCode() {
				if (!validatePhoneNumber(this.phoneNumber)) {
					return;
				}
				if (this.isSend) {
					uni.showToast({
						title: '验证码已发送，请稍后重发',
						icon: 'none',
					})
					return;
				}
				this.isSend = true;
				getCode(this.type, this.phoneNumber).then(result => {
					this.handleCode(result?.data);
				});

			},
		}
	}
</script>

<style scoped lang="scss">
	.code-input-container {
		.send-verification-code {
			white-space: nowrap;
			color: #559df1;
			font-size: 32rpx;
		}
	}
</style>